#include "./draw_tank_task.h"
#include "../heat_driver/ctrl.h"
#include "../heat_driver/sensor.h"
#include "../cfg/heat_info.h"

namespace heat_task {

using namespace heat_driver;
using namespace cfg;

DrawTankTask drawTankTask;


void DrawTankTask::init_start() {
    m_mq.init();
    m_flags.init();
    start();
}

void DrawTankTask::run() {

    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::WORK: do_work(); break;
            case State::STOP: do_stop(); break;
            case State::TIMEOUT:
            case State::FAIL: do_fail(); break;
        }
    }
}

void DrawTankTask::do_idle() {

    for (;;) {

        if (!sensor.is_tank_high()) {
            m_state = State::WORK;
            break;
        }

        if (wait(500)) {
            break;
        }
    }
}

void DrawTankTask::do_work() {

    uint32_t time_count = 0;

    switch (m_tank_state) {
        case TankState::TANK1: ctrl.open(Ctrl::Parts::P1); break;
        case TankState::TANK2: ctrl.open(Ctrl::Parts::P2); break;
        case TankState::FAIL: {
            m_state = State::TIMEOUT;
            goto finish;
        } 
    }

    for (;;) {

        if (sensor.is_tank_high()) {
            m_state = State::IDLE;
            goto finish;
        }

        if (wait(500)) {
            goto finish;
        }
        time_count += 500;

        if (time_count >= heatInfo->tank_draw_time) {
            if (m_tank_state == TankState::TANK1) {
                m_tank_state = TankState::TANK2;
                m_state = State::WORK;
            } else {
                m_tank_state = TankState::FAIL;
                m_state = State::TIMEOUT;
            } 
            goto finish;
        }
    }

finish:
    ctrl.close(Ctrl::Parts::P1);
    ctrl.close(Ctrl::Parts::P2);
}

void DrawTankTask::do_fail() {
    wait();
}

void DrawTankTask::do_stop() {
    m_flags.set_flags(FLAG_STOP);
    wait();
}

}
